﻿using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Warehouse.Domian.Model;
using Warehouse.Infrastructrue.Interface;
using DbType = SqlSugar.DbType;

namespace Warehouse.Infrastructrue.Implenment
{
    public class DbContext : IDbContext,IDisposable
    {
        private readonly IConfiguration _configuration;

        private readonly string _connectionString;

        public SqlSugarScope SqlSugar { get; }

        public IDbConnection DapperConnection { get; }


        public SqlSugarScope SqlSugarScope => throw new NotImplementedException();

        public DbContext(IConfiguration configuration)
        {
            
            _configuration = configuration;
        
            _connectionString = _configuration.GetValue<string>("Connectionstrings_Default");

           
            SqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = _connectionString,
                
                IsAutoCloseConnection = true,
      
                InitKeyType = InitKeyType.Attribute,
               

            },
     
            db =>
            {
            
                db.DbMaintenance.CreateDatabase("WarehouseDatabase");
               
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                };
            });
           
            DapperConnection = new MySqlConnection(_connectionString);
        }
      

        public void InitializeDatabase()
        {
            try
            {
               
                SqlSugar.CodeFirst.InitTables(
                    //库存类型
                    //typeof(Stocking_Type),
                    //入库出库信息表
                    //typeof(Stocking),
                    //移库调拨
                    //typeof(Shifting),
                    //破损
                   // typeof(Breakage),
                    //盘点
                   // typeof(Checksheet)
                   
                    );
                Console.WriteLine("数据库初始化成功！");
            }
            catch
            {
                Console.WriteLine("数据库初始化失败！");
                throw;
            }
        }
       
        public void Dispose()
        {
            DapperConnection?.Dispose();
           
            GC.SuppressFinalize(this);

        }
    }
}
